package com.utility.rsa;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

/**
 * 生成RSA公钥和私钥
 */
public class RSAKeyGenerator {
	/**
	 * 生成的公钥和私钥对中的公钥的key
	 */
	public static final String publicKey = "publicKey";
	/**
	 * 生成的公钥和私钥对中的私钥的key
	 */
	public static final String privateKey = "privateKey";
	/**
	 * 加密方法
	 */
	private static final String ALGORITHM = "RSA";
	
	/**
	 * 生成RSA加密密钥对
	 * @return
	 */
	public static Map<String, String> getKeyPair(){
		try{
			KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);  
			keyPairGen.initialize(512,new SecureRandom());  
			KeyPair keyPair = keyPairGen.generateKeyPair();  
			RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); 
			RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 
			Map<String, String> map = new HashMap<String, String>();
			map.put(RSAKeyGenerator.publicKey, new String(new Base64().encode(publicKey.getEncoded())));
			map.put(RSAKeyGenerator.privateKey, new String(new Base64().encode((privateKey.getEncoded()))));
			return map;
		}catch(NoSuchAlgorithmException e){
			throw new RuntimeException(e);
		}
	}
}
